package com.wanyangproject.shouye;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wanyangproject.R;
import com.wanyangproject.adapter.YuanQuQiYeAdapter;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.widget.suspensionindexbar.IndexBar;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

//public class YuanQuQiYeActivity extends AppCompatActivity {
public class YuanQuQiYeActivity extends AppCompatActivity implements OnRefreshListener, OnLoadmoreListener {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_yuanqu_qiye)
    TextView tvYuanquQiye;
    @BindView(R.id.image_sousuo)
    ImageView imageSousuo;
    @BindView(R.id.relative_sousuo)
    RelativeLayout relativeSousuo;
    @BindView(R.id.et_sousuo)
    EditText etSousuo;
    @BindView(R.id.zimupaixu)
    IndexBar zimupaixu;
    @BindView(R.id.smart)
    SmartRefreshLayout smart;
    private YuanQuQiYeAdapter yuanQuQiYeAdapter;
    private ArrayList<String> suoyin = new ArrayList<>();// 索引A-Z
    private ArrayList<ArrayList<JSONObject>> jsonArrayFenZu = new ArrayList<>();// 分组的数据
    private int page = 0;
    private String zimu;
    private RelativeLayout relativeLayout;
    private LinearLayoutManager manager;
    private JSONObject jsonObject1111;
    private Boolean gundong = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yuan_qu_qi_ye);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View dview = getWindow().getDecorView();
            dview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }


        Intent intent = getIntent();
        zimu = intent.getStringExtra("title");
        System.out.println(zimu + "    字母");



//        List<String> list=new ArrayList<>();
//        list.add("a");
//        list.add("e");
//        list.add("f");
//        list.add("c");
//        list.add("d");
//        list.add("b");
//        //升序
//        //注意：是根据的汉字的拼音的字母排序的，而不是根据汉字一般的排序方法
//        Collections.sort(suoyin, Collator.getInstance(java.util.Locale.CHINA));
//        for (int i=0;i<suoyin.size();i++){
//            System.out.println(suoyin.get(i)+"222==");
//
//        }
//        //降序//不指定排序规则时，也是按照字母的来排序的
//        Collections.reverse(list);
//        for (int i=0;i<list.size();i++){
//            System.out.println(list.get(i)+"333==");
//
//        }



//        园区企业的网络请求
        initYuanQuQiYeHttp();

//                下拉刷新
        smart.setOnRefreshListener(this);
//        上拉加载
        smart.setOnLoadmoreListener(this);


        etSousuo.addTextChangedListener(new TextWatcher() {
            @Override  //   输入文字之前的状态
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override // 输入文字中的状态
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override  // 输入文字之后的状态
            public void afterTextChanged(Editable editable) {
                page = 0;
                //        园区企业的网络请求
                initYuanQuQiYeHttp();
            }
        });






        zimupaixu.setmOnIndexPressedListener(new IndexBar.onIndexPressedListener() {
            @Override
            public void onIndexPressed(int index, String text) {
//                System.out.println(index + "    index");
//                System.out.println(text + "     text");
//                Intent intent0 = new Intent(XuanZeYuanQuActivity.this, YuanQuQiYeActivity.class);
//                intent0.putExtra("title", text);// 点击单个字母传的标题
//                startActivity(intent0);

                System.out.println(jsonObject1111+"          jsonObject1111 ");


                int pos = 0;
                if (suoyin.contains(text)) {
                    int a = suoyin.indexOf(text);
                    int sum = 0;// 之和
                    for (int i = 0; i < a; i++) {
                        ArrayList<JSONObject> jsonObjects = jsonArrayFenZu.get(i);
                        sum += jsonObjects.size();

//                        JSONArray jsonArray = null;
//                        try {
//                            jsonArray = jsonObject1111.getJSONArray(suoyin.get(i));

//                            sum += jsonArray.length();
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
                    }
                    pos = sum;
                    System.out.println(pos + "    pos");
                    recyclerView.setLayoutManager(manager);
//                    manager.scrollToPosition(pos); // 自动滚动到哪一行
                    manager.scrollToPositionWithOffset(pos, 0);// 自动滚动到哪一行
                }
            }

            @Override
            public void onMotionEventEnd() {
                System.out.println("111111111111");
            }
        });

    }


    //    园区企业的网络请求
//    tiantian
//    .addParams("pageIndex","0")
//    .addParams("enterName",etSousuo.getText().toString().trim())
    private void initYuanQuQiYeHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "company")
                .addHeader("token", ContractUtils.getTOKEN(YuanQuQiYeActivity.this))
                .addParams("parkId", ContractUtils.getParkId(YuanQuQiYeActivity.this))
                .addParams("pageIndex", page+"")
                .addParams("enterName", etSousuo.getText().toString().trim())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e + "    eeeeeeeee首页园区企业的网络请求");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "    首页园区企业的网络请求");
                        ContractUtils.Code500(YuanQuQiYeActivity.this, response);
                        if (page == 0) {
                            jsonArrayFenZu.clear();
                            suoyin.clear();
                        }
                        int aa = jsonArrayFenZu.size();


                        try {
//                            tiantiantian
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject jsonObject1 = jsonObject.getJSONObject("response");
                            JSONObject jsonObject2 = jsonObject1.getJSONObject("list");
                            jsonObject1111 = jsonObject2;
                            Iterator<String> keys = jsonObject2.keys();

                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                if (suoyin.contains(key)) {

                                } else {
                                    suoyin.add(key);
                                }
                                // [A,B,C]
                                // []    [ [a]  [b]  []]

                                JSONArray jsonArray = jsonObject2.getJSONArray(key);
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jj = (JSONObject) jsonArray.get(i);
                                    int xiabiao = suoyin.indexOf(key);
                                    if(xiabiao >= jsonArrayFenZu.size()){
                                        ArrayList <JSONObject> jsonObjects = new ArrayList<JSONObject>();
                                        jsonObjects.add(jj);
                                        jsonArrayFenZu.add(jsonObjects);
                                    }else {
                                        jsonArrayFenZu.get(xiabiao).add(jj);
                                    }
                                }
                                int bb = jsonArrayFenZu.size();
                                if (aa == bb) {
//                                    Toast.makeText(YuanQuQiYeActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                                }
//                                suoyin.add(key);

//                                String value = jsonObject.getString(key);
//                                Log.e("TAG", "key=" + key + "\tvalue=" + value);//键值对key value
                                System.out.println(key + "    keykey");
                            }

                            //升序
                            //注意：是根据的汉字的拼音的字母排序的，而不是根据汉字一般的排序方法
                            Collections.sort(suoyin, Collator.getInstance(java.util.Locale.CHINA));
//                            for (int i=0;i<suoyin.size();i++){
//                                System.out.println(suoyin.get(i)+"222==");
//                            }
                            for (int i = 0; i < jsonArrayFenZu.size(); i++) {
                                ArrayList<JSONObject> jsonObjects = jsonArrayFenZu.get(i);
                                JSONObject jsonObject3 = jsonObjects.get(0);
                                String initials = jsonObject3.getString("initials");
                                int xiabiao = suoyin.indexOf(initials);

                                ArrayList<JSONObject> aaa = jsonArrayFenZu.get(xiabiao);
//                                交换
                                ArrayList<JSONObject> set = jsonArrayFenZu.set(xiabiao, jsonArrayFenZu.get(i));
                                ArrayList<JSONObject> set11 = jsonArrayFenZu.set(i, aaa);

                            }
//
                            // A C  B                       A B C
                            // [A] [C] [B]


                            yuanQuQiYeAdapter = new YuanQuQiYeAdapter(YuanQuQiYeActivity.this, jsonArrayFenZu);
                            manager = new LinearLayoutManager(YuanQuQiYeActivity.this);
                            recyclerView.setLayoutManager(manager);
                            recyclerView.setAdapter(yuanQuQiYeAdapter);
                            if(gundong){
                                gundong = false;

                                int pos = 0;
                                for (int i = 0; i < suoyin.size(); i++) {
                                    pos += jsonArrayFenZu.get(i).size();
                                }
                                recyclerView.setLayoutManager(manager);
                                manager.scrollToPosition(pos); // 自动滚动到哪一行
                                System.out.println("gundongsundong"+"        gundongsundong");
                            }


//                            索引
                            int pos = 0;
                            if (suoyin.contains(zimu)) {
                                int a = suoyin.indexOf(zimu);
                                int sum = 0;// 之和
                                for (int i = 0; i < a; i++) {
                                    JSONArray jsonArray = jsonObject2.getJSONArray(suoyin.get(i));
                                    if (jsonArray == null) {
                                        return;
                                    }
                                    sum += jsonArray.length();
                                }
                                pos = sum;
                            }
                            System.out.println(pos + "    pos");
                            recyclerView.setLayoutManager(manager);
                            manager.scrollToPosition(pos); // 自动滚动到哪一行
//                            manager.smoothScrollToPosition(this,,pos);



                            yuanQuQiYeAdapter.setYuanQuQiYeClick(new YuanQuQiYeAdapter.YuanQuQiYeClick() {
                                @Override
                                public void yuanquqiyeClick(int position, String id) {
                                    Intent intent = new Intent(YuanQuQiYeActivity.this, QiYeXiangQingActivity.class);
//                                    应该传企业的id   tian   tian
                                    intent.putExtra("id", id);
                                    startActivity(intent);
                                }
                            });


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


//                        Gson gson = new Gson();
//                        ShouYeYuanQuQiYeEntity shouYeYuanQuQiYeEntity = gson.fromJson(response, ShouYeYuanQuQiYeEntity.class);
//                        if(response.indexOf("200") != -1){
//                            yuanQuQiYeAdapter = new YuanQuQiYeAdapter(YuanQuQiYeActivity.this,shouYeYuanQuQiYeEntity.getResponse().getList());
//                            LinearLayoutManager manager = new LinearLayoutManager(YuanQuQiYeActivity.this);
//                            recyclerView.setLayoutManager(manager);
//                            recyclerView.setAdapter(yuanQuQiYeAdapter);
//
//                            yuanQuQiYeAdapter.setYuanQuQiYeClick(new YuanQuQiYeAdapter.YuanQuQiYeClick() {
//                                @Override
//                                public void yuanquqiyeClick(int position) {
//                                    Intent intent = new Intent(YuanQuQiYeActivity.this, QiYeXiangQingActivity.class);
//                                    startActivity(intent);
//                                }
//                            });
//                        }
                    }
                });
    }


    @OnClick({R.id.tv_yuanqu_qiye, R.id.et_sousuo, R.id.image_sousuo, R.id.relative_sousuo, R.id.image_back, R.id.recyclerView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
//            搜索
            case R.id.et_sousuo:

                break;
            case R.id.recyclerView:
                break;
            case R.id.tv_yuanqu_qiye:
                break;
            case R.id.image_sousuo:
                tvYuanquQiye.setVisibility(View.INVISIBLE);
                relativeSousuo.setVisibility(View.VISIBLE);
                imageSousuo.setVisibility(View.INVISIBLE);
                break;
            case R.id.relative_sousuo:
                break;
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        page = 0;
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 0;
        //        园区企业的网络请求
        initYuanQuQiYeHttp();
        if (refreshlayout.isRefreshing()) {
            refreshlayout.finishRefresh();
        }
    }


    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page++;
        gundong = true;
//        //        园区企业的网络请求
        initYuanQuQiYeHttp();
        refreshlayout.finishLoadmore();

    }
}
